<template>
  <div class="app-container">
    <el-row class="pagecenter">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="企业法定地址">
          <el-select v-model="province" placeholder="请选择省" class="selectStyle">
            <el-option v-for="item in position.province.list" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
          <el-select v-model="city" placeholder="请选择市" class="selectStyle">
            <el-option v-for="item in position.city.list" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
          <!-- <el-select v-model="town" placeholder="请选择县" class="selectStyle" :disabled="false">
                                <el-option v-for="item in position.town.list" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                              </el-select> -->
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="listQuery.auditStatus" placeholder="审核状态" class="selectStyle">
            <el-option v-for="item in enterpriseStatus" :key="item.dictvalue" :label="item.dictname" :value="item.dictvalue"></el-option>            
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="listQuery.orderBy" placeholder="默认" class="selectStyle">
            <!-- <el-option label="默认" value=""></el-option> -->
            <!-- <el-option label="最近登录" value="最近登录"></el-option>
            <el-option label="最近更新" value="最近更新"></el-option>  -->
            <el-option v-for="item in enterpriseOrders" :key="item.dictvalue" :label="item.dictname" :value="item.dictvalue"></el-option>            
          </el-select>
        </el-form-item>
        <el-form-item label="关键词查询">
          <el-input placeholder="企业名称或账号名称" v-model="listQuery.enterprisenameOrUsername" :maxlength="50" @keyup.enter.native="fetchData"></el-input>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row>
      <div class="btnGroup">
        <el-button @click="fetchData" icon="search">查询</el-button>
        <el-button @click="resetFetch">
          <icon-svg icon-class="zhongzhi1"></icon-svg>&nbsp;&nbsp;重置条件</el-button>
        <el-button @click="handleExcel" v-show="btnVisible.isExport">
          <icon-svg icon-class="Excel4"></icon-svg>&nbsp;&nbsp;导出excel</el-button>
        <el-button @click="handleRecycle" v-show="btnVisible.isRecycle">
          <icon-svg icon-class="huishouzhan"></icon-svg>&nbsp;&nbsp;回收站</el-button>

        <!-- <el-button @click="testSupportReq">
                    <icon-svg icon-class="zhengshu4"></icon-svg>&nbsp;&nbsp;支撑测试</el-button> -->

        <span class="createBtn" v-show="btnVisible.isAdd">
          <el-button @click="addEnterprise">
            <icon-svg icon-class="xinjian"></icon-svg>&nbsp;&nbsp;新建企业</el-button>
        </span>
      </div>
    </el-row>
    <el-row class="pageborder">
      <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" highlight-current-row tooltip-effect="dark" style="width: 100%" :fit="true">
        <el-table-column label='序号' min-width="80" align="center">
          <template scope="scope">
            {{ page.pageSize * (page.currentPage - 1) + scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column label="企业编号" min-width="100" header-align="center" align="left">
          <template scope="scope">
            {{scope.row.enterpriseid}}
          </template>
        </el-table-column>
        <el-table-column label="企业名称" min-width="300" :show-overflow-tooltip="true" header-align="center" align="left">
          <template scope="scope">
            {{scope.row.enterprisename}}
          </template>
        </el-table-column>
        <el-table-column label="注册时间" min-width="180" header-align="center" align="left">
          <template scope="scope">
            {{scope.row.createdate}}
          </template>
        </el-table-column>
        <el-table-column label="追溯码数量" min-width="120" header-align="center" align="right">
          <template scope="scope">
            {{scope.row.tracecodequantity}}
          </template>
        </el-table-column>
        <el-table-column label="验证码(已用/剩余)" min-width="160" header-align="center" align="right">
          <template scope="scope">
            {{scope.row.fakenumberremain}}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="100" header-align="center" align="center">
          <template scope="scope">
            {{scope.row.auditstatus}}
          </template>
        </el-table-column>
        <el-table-column label="最近登录时间" min-width="180" header-align="center" align="left">
          <template scope="scope">
            {{scope.row.lastlogindate}}
          </template>
        </el-table-column>
        <el-table-column label="最近更新时间" min-width="180" header-align="center" align="left">
          <template scope="scope">
            {{scope.row.updatedate}}
          </template>
        </el-table-column>
        <el-table-column label="登录账号" min-width="150" :show-overflow-tooltip="true" header-align="center" align="left">
          <template scope="scope">
            <span>{{scope.row.username}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="280" header-align="center" align="center">
          <template scope="scope">
            <el-button type="small" @click="viewEnterprise(scope.$index,scope.row)" v-show="btnVisible.isView">
              <icon-svg icon-class="view"></icon-svg>&nbsp;&nbsp;查看</el-button>
            <el-button icon="edit" type="small" @click="editEnterprise(scope.$index,scope.row)" v-show="btnVisible.isEdit">编辑</el-button>
            <el-button icon="delete" type="small" @click="deleteEnterprise(scope.$index,scope.row)" v-show="btnVisible.isDelete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="pagination" v-if="page.total > 0 ? true : false">
      <el-pagination @current-change="handleCurrentChange" :page-size="page.pageSize" :current-page.sync="page.currentPage" layout="total, prev, pager, next, jumper" :total="page.total">
      </el-pagination>
    </el-row>
  </div>
</template>

<style scoped>
.pagination {
  text-align: center;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.colSpace {
  margin-left: 5px;
}

.cardbody {
  margin-top: 0px;
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}

.cardup {
  padding: 1px 10px;
  border-top: 1px solid #ddd;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
}

.cardcontent {
  color: white;
}

.yesterday {
  font-size: 14px;
}

.carddown {
  padding: 10px 10px;
  background-color: #f5f5f5;
  border-top: 1px solid #ddd;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
}

td {
  overflow: hidden;
  text-overflow: ellipsis;
}

.viewBtn {
  float: right;
}

.selectStyle {
  width: 145px;
}

.btnGroup {
  margin-bottom: 15px;
}

.createBtn {
  float: right;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>

<script>
import { getList, deleteEnterprise, enterpriseStatus } from 'api/enterprise';
import { supportedLogin, supportedSelectListByPage } from 'api/supporttest';
import { getPositionList, getEnterpriseOrdersList } from 'api/system';
import { parseTime } from 'utils/index';
import { btnIsVisible, getUrlParams, trimStr } from 'utils/customer';
import Cookies from 'js-cookie';

export default {
  data() {
    return {
      list: [],
      listQuery: {
        statutoryAddress: null,
        auditStatus: '',
        orderBy: '',
        enterprisenameOrUsername: '',
        deleted: 0
      },
      page: {
        pageSize: null,
        total: null,
        totalPage: null,
        currentPage: null
      },
      listLoading: true,
      position: {
        province: {
          list: [],
          isEnable: false
        },
        city: {
          list: [],
          isEnable: true
        }
      },
      province: null,
      city: null,
      addressPosition: {
        province: '',
        city: '',
        county: '',
        town: '',
        provinceList: null,
        cityList: null,
        countyList: null,
        townList: null
      },
      productPosition: {
        province: '',
        city: '',
        county: '',
        town: '',
        provinceList: null,
        cityList: null,
        countyList: null,
        townList: null
      },
      btnVisible: {
        isAdd: false,
        isView: false,
        isEdit: false,
        isDelete: false,
        isExport: false,
        isRecycle: false
      },
      excelParams: '',
      excelUrl: '',
      enterpriseStatus: [],
      enterpriseOrders: []
    }
  },
  watch: {
    province() {
      this.getPosition(2);
      this.position.city.list = null; this.city = null;
      this.listQuery.statutoryAddress = this.province
    },
    city() {
      this.listQuery.statutoryAddress = this.city
    },
    'listQuery.auditStatus': function(val,oldval) {
      if (val) {
        this.handleCurrentChange(1)
      } else {
        if (!val && oldval) {
          this.handleCurrentChange(1)
        }
      }
    },
    'listQuery.orderBy': function(val) {
      if (val) {
        this.handleCurrentChange(1)
      }
    },
    'listQuery.statutoryAddress': function(val, oldval) {
      if (val || (oldval && !val)) {
        this.handleCurrentChange(1)
      }
    },
    // 'listQuery.enterprisenameOrUsername': function(val) {
    //   this.page.currentPage = 1
    // },
  },
  created() {
    // this.getProductType();
    this.getPosition(1);
    this.fetchData();
    this.getEnterpriseStatus();
    this.getBtnVisbleStatus();
    this.enterpriseOrdersList();
  },
  methods: {
    getBtnVisbleStatus() {
      this.btnVisible.isView = btnIsVisible('ENTERPRISE_LIST_VIEW') || false;
      this.btnVisible.isAdd = btnIsVisible('ENTERPRISE_LIST_INSERT') || false;
      this.btnVisible.isEdit = btnIsVisible('ENTERPRISE_LIST_UPDATE') || false;
      this.btnVisible.isDelete = btnIsVisible('ENTERPRISE_LIST_DELETE') || false;
      this.btnVisible.isExport = btnIsVisible('ENTERPRISE_LIST_EXPORT') || false;
      this.btnVisible.isRecycle = btnIsVisible('ENTERPRISE_LIST_RECYCLE') || false;
    },
    enterpriseOrdersList() {
      getEnterpriseOrdersList().then(response => {
        let res = response.data;
        if (res.flag === 1) {
          this.enterpriseOrders = res.data
        }
      })
    },
    getEnterpriseStatus() {
      enterpriseStatus().then(response => {
        let res = response.data;
        if (res.flag === 1) {
          this.enterpriseStatus = res.data;
        }
      })
    },
    getPosition(level) {
      let pisCode = null;
      switch (level) {
        case 1: pisCode = null; break;
        case 2: pisCode = this.province; break;
        // case 3: pisCode = this.city; break;
        default: break;
      };
      let parentcode = {
        parentcode: pisCode
      };
      getPositionList(parentcode).then(response => {
        let res = response.data;
        if (res.flag === 1) {
          switch (level) {
            case 1: this.position.province.list = res.data; break;
            case 2: this.position.city.list = res.data; break;
            default: break;
          }
        }
      })
    },
    resetFetch() {
      this.listQuery.type = '';
      this.city = null;
      this.province = null;
      this.listQuery.statutoryAddress = null;
      this.listQuery.auditStatus = null;
      this.listQuery.orderBy = null;
      this.listQuery.enterprisenameOrUsername = null;
      this.handleCurrentChange(1)
    },
    fetchData() {
      this.listLoading = true;
      this.page.pageSize = this.page.pageSize || 10;
      this.page.currentPage = this.page.currentPage || 1;
      this.listQuery.currentPage = this.page.currentPage;
      this.listQuery.pageSize = this.page.pageSize;
      // this.listQuery.type = this.listQuery.type || '';
      // if (this.dateScope) {
      //   this.listQuery.createdatestart = parseTime(this.dateScope[0]);
      //   this.listQuery.createdateend = parseTime(this.dateScope[1]);
      // }
      this.listQuery.statutoryAddress = this.city || this.province;
      this.listQuery.auditStatus = this.listQuery.auditStatus || '';
      this.listQuery.orderBy = this.listQuery.orderBy || '';
      this.listQuery.enterprisenameOrUsername = trimStr(this.listQuery.enterprisenameOrUsername) || '';
      this.excelParams = getUrlParams(this.listQuery)
      getList(this.listQuery).then(response => {
        let res = response.data;
        if (res.flag) {
          this.list = res.data;
          this.page = res.page;
        }
        this.listLoading = false;
      })
    },
    handleExcel() {
      if (this.list.length <= 0) return;
      this.excelUrl = '/trc-service-enterprise/enterprise/exportEnterprise' + this.excelParams;
      window.location.href = this.excelUrl;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleDivisionChange(val) {
      // console.log(val);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.fetchData();
    },
    editEnterprise(index, row) {
      this.initAddressPosition(row.productionAddressPositionList, this.addressPosition);
      this.initAddressPosition(row.addressPositionList, this.productPosition);
      this.$router.push({ path: 'enterpriseedit', query: { enterpriseinfo: row, addressPosition: this.addressPosition, productPosition: this.productPosition } })
    },
    addEnterprise() {
      this.$router.push({ path: 'enterpriseadd' });
    },
    viewEnterprise(index, row) {
      this.$router.push({ path: 'enterpriseview', query: { enterpriseinfo: row, deleted: 0 } })
    },
    deleteEnterprise(index, row) {
      this.$confirm('此操作将会把该记录放入回收站, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let requestParam = {
          enterpriseid: row.enterpriseid
        }
        deleteEnterprise(requestParam).then(response => {
          let res = response.data;
          if (res.flag == 1) {
            this.fetchData();
            this.$message({
              showClose: true,
              message: '删除企业信息成功',
              type: 'success'
            });
          } else {
            this.$message({
              showClose: true,
              message: '删除企业信息失败',
              type: 'error'
            });
          }
        })
      }).catch(() => {
      });
      // let requestParam = {
      //   enterpriseid: row.enterpriseid
      // }
      // deleteEnterprise(requestParam).then(response => {
      //   let res = response.data;
      //   if (res.flag == 1) {
      //     this.fetchData();
      //     this.$message({
      //       showClose: true,
      //       message: '删除信息成功',
      //       type: 'success'
      //     });
      //   } else {
      //     this.$message({
      //       showClose: true,
      //       message: '删除信息失败',
      //       type: 'error'
      //     });
      //   }
      // })
    },
    initAddressPosition(positionList, position) {
      if (!positionList) return;
      let addr = positionList;
      let addrLen = addr.length || 0;
      switch (addrLen) {
        case 1:
          position.provinceList = addr[0].children;
          position.province = addr[0].code;
          break;
        case 2:
          position.provinceList = addr[0].children;
          position.cityList = addr[1].children;
          position.province = addr[0].code;
          position.city = addr[1].code;
          break;
        case 3:
          position.provinceList = addr[0].children;
          position.cityList = addr[1].children;
          position.countyList = addr[2].children;
          position.province = addr[0].code;
          position.city = addr[1].code;
          position.county = addr[2].code;
          break;
        case 4:
          position.provinceList = addr[0].children;
          position.cityList = addr[1].children;
          position.countyList = addr[2].children;
          position.townList = addr[3].children;
          position.province = addr[0].code;
          position.city = addr[1].code;
          position.county = addr[2].code;
          position.town = addr[3].code;
          position.changeFlag = true;
          break;
        default:
          break;
      }
    },
    handleRecycle() {
      // 导航到回收站
      this.$router.push({ path: 'enterpriserecycle' })
    },

    // 支撑平台接口测试
    testSupportReq() {
      supportedLogin().then(response => {
        let res = response.data;
        if (res.error === 0) {
          console.log('支撑登录成功.' + res);
          supportedSelectListByPage().then(response => {
            let res2 = response.data;
            if (res2.error === 0) {
              console.log('访问数据成功.' + res2);
            }
          })
        }
      })
    }
  }
};
</script>